# -*- coding: utf-8 -*-
class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :login_from_cookie
  before_filter :set_current_user
  before_filter :set_locale
  before_filter :set_timezone

private
  def login_from_cookie
    return if logged?() || cookies[:auth_token].nil?
    @current_user = User.find_by_remember_token(cookies[:auth_token])
    if @current_user && (@current_user.remember_expires_at > Time.now)
      @current_user.login! session
      @current_user.remember_me cookies
    end
  end

  def set_current_user
    @current_user = logged? ? User.find( session[:user_id] ) : nil unless @current_user
  end

  def set_locale
    req_lang = request.env['HTTP_ACCEPT_LANGUAGE']
    req_lang = req_lang.nil? ? nil : req_lang[/[^,;]+/]
    session[:locale] = case
             when Republic::Application::VALID_LANG.include?(params[:locale]) then params[:locale]
             when session[:locale] then session[:locale]
             when Republic::Application::VALID_LANG.include?(req_lang) then req_lang
             end
    I18n.locale = session[:locale] || I18n.default_locale
  end

  def set_timezone
    if logged? && @current_user.time_zone
      Time.zone = @current_user.time_zone
    end
  end

protected
  def current_user_must_be_admin
    redirect_to_login t('errors.not_admin') unless current_user_is_admin?
  end

## TODO 权限管理
  def current_user_is_admin?
    @current_user && (@current_user.id == 1)
  end

  def redirect_to_register notice
    flash[:alert] = notice
    session[:last_uri] = request.request_uri
    redirect_to login_path
  end

  def redirect_to_login notice
    flash[:alert] = notice
    session[:last_uri] = request.request_uri
    redirect_to login_path
  end

helper_method :logged?, :last_uri
  def logged? *user
    if user.count == 0
      not session[:user_id].nil?
    else
      session[:user_id] == user[0].id
    end
  end

  def last_uri
    session_uri = session[:last_uri]
    session[:last_uri] = nil
    session_uri || params[:last_uri] || root_path
  end

end
